<template lang="pug">
.page
  .SpecialAdditionalDeductions
    .search-form.mb-10.pr-10
      Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90")
        FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
          template(v-if="item.type === 'select'")
            Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
              Option(
                v-for="(c_item, index) in arrListDown[item.options]"
                :value="c_item.value"
                :key="index"
              ) {{ c_item.label }}
          template(v-if="item.type === 'input'")
            Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
          template(v-if="item.type === 'datePicker'")
            DatePicker.w-100(:value="formData[item.model]" :placeholder="item.placeholder" type="month" @on-change="handleChangeDatePicker(item.model, $event)")
          template(v-if="item.type === 'datePickerTax'")
            DatePicker.pull-left.interval-date-140(:value="formData.taxBeginMonth" placeholder="开始日期" type="month" @on-change="handleChangeDatePicker('taxBeginMonth', $event)")
            span.pl-10.pr-10.pull-left.line-h-32 --
          template(v-if="item.type === 'datePickerTax'")
            DatePicker.pull-left.interval-date-140.mr-20(:value="formData.taxEndMonth" placeholder="结束日期" type="month" @on-change="handleChangeDatePicker('taxEndMonth', $event)")
          template(v-if="item.type === 'cascader'")
            .areaTree
              Cascader(v-model="formData[item.model]" :data="areaTree" clearable change-on-select @on-change="areaTreeChange(item.model, $event)")
          template(v-if="item.type === 'button'")
            Button(v-if="hasFind" type="info" @click="searchFn") 查询

    .pl-20.pr-20.bg-white
      Table.hasTitle-table.beautiful-table(:columns="setThead" :data="tableData" :stripe="true"
        @on-selection-change="handleOnSelectChange"
      )
        .clearfix.font-16(slot="header")
          .table-title-lefttxt.pull-left
            |合计
            span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
            |条
          .pull-right.table-title-btns
            Button.mr-10(v-if="hasImport" type="info" ghost @click="handleShowSpecialImportModal") 导入
            Button.mr-10(v-if="hasExport" type="info" ghost @click="handleExport") 导出

        .clearfix.pl-20.pr-20(slot="footer")  
          Page(
            :current="tableComone.pageIndex"
            :total="tableComone.totalRows"
            @on-change="onChangePage"
            @on-page-size-change="onpageSizeChange"
            show-sizer
            show-total
            placement="top"
            prev-text="上一页"
            next-text="下一页"
            :page-size-opts="[10, 20, 30, 50, 100]"
          )
    SpecialImportModal(ref="SpecialImportModal" @query="searchFn")
</template>

<script>
import { Common } from '@/utils/common.js'
// import { SpecialAdditionalDeductionsApi } from '@/api/SpecialAdditionalDeductions.api.js'
// import { EmployeeSalaryApi } from '@/api/EmployeeSalary.api.js'
import { EmployeeSpecialDeductApi } from '@/api/EmployeeSpecialDeduct.api.js'

import { specialThead } from '../../CStableHead.js'
import _cloneDeep from 'clone-deep'
import SpecialImportModal from '../../modal/specialImportModal.vue'
// import BackModal from './modal/backModal.vue'
import { ProvinceList, AreaTree } from '@/utils/publicJson.js'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')
export default {
  name: 'SpecialAdditionalDeductions',

  components: {
    SpecialImportModal
    // BackModal
  },

  data () {
    return {
      thead: _cloneDeep(specialThead),
      tableData: [],
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10 // 当前页面展示条数
      },
      formData: {
        name: '',
        month: new Date(),
        cooperateType: '',
        cityId: [],
        serverId: '',
        taskStatus: '',
        salaryBeginMonth: new Date().getFullYear()+'-'+(new Date().getMonth()+1),
        salaryEndMonth: new Date().getFullYear()+'-'+(new Date().getMonth()+1),
        taxBeginMonth: '',
        taxEndMonth: ''
      },
      formItem: [
        { type: 'input', label: '身份证号码：', placeholder: '请输入身份证号码', prop: 'idCardNo', model: 'idCardNo', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'datePicker', label: '所属月份：', placeholder: '所属月份', prop: 'month', model: 'month', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'input', label: '公司名称：', placeholder: '请输入公司名称', prop: 'customerName', model: 'customerName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-4' }
      ],
      rules: {},
      arrListDown: {
        type: [],
        server: [],
        status: [],
        taxs: []
      },
      areaArr: [], // 区域数组
      selectedId: '', // 勾选的id集合
      selectedIdArr: [], // 勾选的id, name数组集合
      axsEnableSwitch: false,
      // errorData: {
      //   errorId: '',
      //   isError: false
      // },
      // downLoadUrl: '/api/SpecialAdditionalDeductions/ExportErrorFile?fileName='
      areaTree: [], // 中国所有城市树
      backReason: ''
    }
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 导出明细
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    },
    // 导入
    hasImport () {
      return this.actionArr.indexOf('Import') > -1
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    },

    setThead () {
      if (!this.axsEnableSwitch) {
        // return [...this.thead.slice(0, 7), ...this.thead.slice(8, this.thead.length + 1)]
        return this.thead
      } else {
        return [...this.thead.slice(0, 3), ...this.thead.slice(4, this.thead.length + 1)]
      }
    },

    setFormItem () {
      if (this.axsEnableSwitch) {
        return this.formItem
      } else {
        return [...this.formItem.slice(0, 5), ...this.formItem.slice(6, this.formItem.length + 1)]
      }
    }
  },

  watch: {
  },

  mounted () {
    this.servers()
    this.getEnum()
    this.query()
  },

  methods: {

    // 数据字典
    getEnum () {
      let groupName = 'customer.type,customersalary.status'
      Common.getEnum(groupName, this.arrListDown)
      console.log('数据字典：', this.arrListDown)
    },

    // 获取客服
    async servers () {
      var params = {
        PageIndex: 1,
        PageSize: 100,
        Args: ''
      }
      Common.servers(params, this.arrListDown, 'server')
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        idCardNo: this.formData.idCardNo,
        month: this.formData.month,
        customerName: this.formData.customerName,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
      }
      let res = await EmployeeSpecialDeductApi.getList(params)
      console.log('客户薪资res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        // this.axsEnableSwitch = res.data.axsEnableSwitch
        this.selectedIdArr = []
        this.selectedId = ''
      } else {
        this.tableData = []
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
      this.loading = false
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    // 导入薪资弹窗
    handleShowSpecialAdditionalDeductionsImportModal () {
      this.$refs.SpecialAdditionalDeductionsImportModal.show() // 显示弹窗
      this.$refs.SpecialAdditionalDeductionsImportModal.errorData.isError = false // 隐藏错误数据下载按钮
      this.$refs.SpecialAdditionalDeductionsImportModal.isCanUpload = true // 可导入按钮
      this.$refs.SpecialAdditionalDeductionsImportModal.salaryStartTimeDefault = new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1), // 上个月1号
      this.$refs.SpecialAdditionalDeductionsImportModal.salaryEndTimeDefault = new Date(new Date().getFullYear(), new Date().getMonth() - 1, 30), // 上个月30号
      this.$refs.SpecialAdditionalDeductionsImportModal.handleClearFiles()
    },

    handleShowSpecialAdditionalDeductionsResultImportModal () {
      this.$refs.SpecialAdditionalDeductionsResultImportModal.show() // 显示弹窗
      this.$refs.SpecialAdditionalDeductionsResultImportModal.errorData.isError = false // 隐藏错误数据下载按钮
      this.$refs.SpecialAdditionalDeductionsResultImportModal.isCanUpload = true // 可导入按钮
      this.$refs.SpecialAdditionalDeductionsResultImportModal.salaryStartTimeDefault = new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1), // 上个月1号
      this.$refs.SpecialAdditionalDeductionsResultImportModal.salaryEndTimeDefault = new Date(new Date().getFullYear(), new Date().getMonth() - 1, 30), // 上个月30号
      this.$refs.SpecialAdditionalDeductionsResultImportModal.handleClearFiles()
    },

    // 批量导入-显示弹窗
    handleShowBatchImportSalaryModal () {
      this.$refs.BatchImportSalaryModal.show()
      this.$refs.BatchImportSalaryModal.file = null
      this.$refs.BatchImportSalaryModal.errorData.isError = false
      // this.$refs.BatchImportSalaryModal.year = this.$moment(this.tableData[0].salaryMonth).format('YYYY')
    },

    // 退回-显示弹窗
    handleShowBackModal (row) {
      console.log('row: ', row)
      this.$refs.BackModal.show(row)
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedIdArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      let arr = value.map((item) => {
        return item.id
      })
      this.selectedId = arr.join(',')
      console.log('列表勾选数组', this.selectedIdArr)
      console.log('列表勾选数组字符串', this.selectedId)
    },

    // 日期选择
    datePickerChange (e) {
      this.formData.month = e
    },

    // 时间控件
    handleChangeDatePicker (model, value) {
      this.formData[model] = value
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    },

    // 导出
    async handleExport (exportType) {
      var params = {
        ids: this.selectedId,
        idCardNo: this.formData.idCardNo,
        month: this.formData.month,
        customerName: this.formData.customerName,
      }
      EmployeeSpecialDeductApi.export(params).then(res => {
        console.log('导出: ', res)
        if (res.status === 200 && res.data.success) {
          console.log('❤ 返回链接: ', baseUrl + res.data.data)
          window.open(baseUrl + res.data.data, '_blank')
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },

    // 批量导入-显示弹窗
    handleShowSpecialImportModal () {
      this.$refs.SpecialImportModal.show()
      this.$refs.SpecialImportModal.file = null
      this.$refs.SpecialImportModal.errorData.isError = false
    },
  }
}
</script>

<style lang="less" scope>
</style>
